<template>
  <div>
    <el-dialog
      :title="
        mode === 'detail'
          ? '会员企业人员信息采集→人员信息详情'
          : '会员企业人员信息采集→新增人员信息'
      "
      :visible.sync="show"
      :before-close="close"
      width="90%"
      :append-to-body="true"
      top="5vh"
    >
      <div class="button-group" v-if="mode !== 'detail'">
        <el-button type="primary" size="small" @click="addRow"
          >新增人员</el-button
        >
      </div>

      <el-table :data="personnelList" border stripe max-height="500">
        <el-table-column
          label="序号"
          align="center"
          type="index"
          width="60"
        ></el-table-column>
        <el-table-column label="人员姓名" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.operatorName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="人员性质" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.opType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.opGender }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.opAge }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最高学历" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.highestDegree }}</span>
          </template>
        </el-table-column>
        <el-table-column label="职称" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.opPosition }}</span>
          </template>
        </el-table-column>
        <el-table-column label="持证名称" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.certificateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="证件编号" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.certificateNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发证单位" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.certificateUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="负责模块" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.opDuty }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="mode !== 'detail'"
          label="操作"
          align="center"
          width="150"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="editRow(scope.row, scope.$index)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              style="color: #f56c6c"
              @click="deleteRow(scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <!-- <pagination
        v-show="personnelList.length > 0"
        :total="personnelList.length"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handlePagination"
        class="pagination-container"
      /> -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="close" size="small">取消</el-button>
      </span>
    </el-dialog>

    <!-- 人员信息对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增人员信息' : '编辑人员信息'"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      width="800px"
      :append-to-body="true"
    >
      <el-form :model="form" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人员姓名">
              <el-input
                v-model="form.operatorName"
                placeholder="请输入人员姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员性质">
              <el-select
                v-model="form.opType"
                placeholder="请选择人员性质"
                style="width: 100%"
              >
                <el-option label="管理人员" value="管理人员"></el-option>
                <el-option label="技术人员" value="技术人员"></el-option>
                <el-option label="其他人员" value="其他人员"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select
                v-model="form.opGender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄">
              <el-input
                v-model="form.opAge"
                placeholder="请输入年龄"
                type="number"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历">
              <el-select
                v-model="form.highestDegree"
                placeholder="请选择最高学历"
                style="width: 100%"
              >
                <el-option label="博士" value="博士"></el-option>
                <el-option label="硕士" value="硕士"></el-option>
                <el-option label="本科" value="本科"></el-option>
                <el-option label="大专" value="大专"></el-option>
                <el-option label="高中" value="高中"></el-option>
                <el-option label="初中及以下" value="初中及以下"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称">
              <el-input
                v-model="form.opPosition"
                placeholder="请输入职称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="持证名称">
              <el-input
                v-model="form.certificateName"
                placeholder="请输入持证名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件编号">
              <el-input
                v-model="form.certificateNum"
                placeholder="请输入证件编号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发证单位">
              <el-input
                v-model="form.certificateUnit"
                placeholder="请输入发证单位"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责模块">
              <el-input
                v-model="form.opDuty"
                placeholder="请输入任务单负责模块"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="small">取消</el-button>
        <el-button
          type="primary"
          @click="saveDialog"
          size="small"
          :loading="dialogLoading"
        >
          {{ dialogType === "add" ? "保存" : "保存" }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  companyOperatorAddOp, // 新增人员信息
  companyOperatorUpdate, // 新增人员信息-编辑
  companyOperatorQueryByApplyCode, // 根据申请编号查询本申请详细信息
  companyOperatorDelOp, // 防治公司删除人员信息-（申请单状态需在编辑状态下）
} from "@/api/manage/approval";
export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    detailForm: {
      type: Object,
      default: () => ({}),
    },
    mode: {
      type: String,
      default: "edit", // 'edit' 或 'detail'
    },
  },
  data() {
    return {
      personnelList: [],
      dialogVisible: false,
      dialogType: "add", // 'add' or 'edit'
      currentIndex: -1,
      form: {
        operatorName: "",
        opType: "",
        opGender: "",
        opAge: "",
        highestDegree: "",
        opPosition: "",
        certificateName: "",
        certificateNum: "",
        certificateUnit: "",
        opDuty: "",
        operatorId: "",
      },
      dialogLoading: false,
      queryParams: {
        // pageNum: 1,
        // pageSize: 5,
        formNum: this.detailForm.formNum,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      companyOperatorQueryByApplyCode(this.queryParams).then((res) => {
        if (res.errorCode === "000000") {
          this.personnelList = res.data.response;
        }
      });
    },
    close() {
      this.$emit("closeMsg");
    },
    handleConfirm() {
      // 验证数据
      let hasError = false;
      for (let i = 0; i < this.personnelList.length; i++) {
        const item = this.personnelList[i];
        if (!item.operatorName) {
          this.$modal.msgWarning(`第${i + 1}行人员姓名不能为空`);
          hasError = true;
          break;
        }
        if (!item.opType) {
          this.$modal.msgWarning(`第${i + 1}行人员性质不能为空`);
          hasError = true;
          break;
        }
      }

      if (!hasError) {
        this.$emit("closeMsg", this.personnelList);
        this.$modal.msgSuccess("保存成功");
      }
    },
    addRow() {
      // 清空表单并设置为新增模式
      this.form = {
        operatorName: "",
        opType: "",
        opGender: "",
        opAge: "",
        highestDegree: "",
        opPosition: "",
        certificateName: "",
        certificateNum: "",
        certificateUnit: "",
        opDuty: "",
        operatorId: "",
      };
      this.dialogType = "add";
      this.currentIndex = -1;
      this.dialogVisible = true;
    },
    deleteRow(row, index) {
      const data = {
        controlId: this.detailForm.controlId,
        operatorId: row.operatorId,
      };
      this.$modal
        .confirm("是否确认删除该人员？")
        .then(() => {
          return companyOperatorDelOp(data);
        })
        .then((res) => {
          if (res.errorCode === "000000") {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          } else {
            this.$modal.msgError(res.errorMsg || "删除失败");
          }
        })
        .catch((error) => {
          // 如果用户取消确认，不显示错误
          if (error !== "cancel") {
            this.$modal.msgError("删除失败，请稍后重试");
          }
        });
    },
    editRow(row, index) {
      this.form = { ...row };
      this.dialogType = "edit";
      this.currentIndex = index;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.form = {
        operatorName: "",
        opType: "",
        opGender: "",
        opAge: "",
        highestDegree: "",
        opPosition: "",
        certificateName: "",
        certificateNum: "",
        certificateUnit: "",
        opDuty: "",
        operatorId: "",
      };
      this.dialogType = "add";
      this.currentIndex = -1;
      this.dialogLoading = false;
    },
    saveDialog() {
      if (!this.form.operatorName) {
        this.$modal.msgWarning("人员姓名不能为空");
        return;
      }
      if (!this.form.opType) {
        this.$modal.msgWarning("人员性质不能为空");
        return;
      }

      if (this.dialogType === "add") {
        const payload = {
          ...this.form,
          formNum: this.queryParams.formNum,
          controlId: this.detailForm.controlId,
          approvalType: this.detailForm.approvalType,
        };
        this.dialogLoading = true;
        companyOperatorAddOp(payload)
          .then((res) => {
            if (res.errorCode === "000000") {
              this.$modal.msgSuccess("新增人员成功");
              this.getList();
              this.closeDialog();
            } else {
              this.$modal.msgError(res.errorMsg || "新增人员失败");
            }
          })
          .catch(() => {
            this.$modal.msgError("新增人员失败");
          })
          .finally(() => {
            this.dialogLoading = false;
          });
      } else if (this.dialogType === "edit") {
        const payload = {
          ...this.form,
          formNum: this.queryParams.formNum,
          controlId: this.detailForm.controlId,
          approvalType: this.detailForm.approvalType,
        };
        if (!payload.operatorId) {
          this.$modal.msgError("缺少人员标识，无法编辑");
          return;
        }
        this.dialogLoading = true;
        companyOperatorUpdate(payload)
          .then((res) => {
            if (res.errorCode === "000000") {
              this.$modal.msgSuccess("编辑成功");
              this.getList();
              this.closeDialog();
            } else {
              this.$modal.msgError(res.errorMsg || "编辑失败");
            }
          })
          .catch(() => {
            this.$modal.msgError("编辑失败");
          })
          .finally(() => {
            this.dialogLoading = false;
          });
      }
    },
    handlePagination(params) {
      this.queryParams.pageNum = params.page;
      this.queryParams.pageSize = params.limit;
    },
  },
};
</script>

<style lang="scss" scoped>
.button-group {
  margin-bottom: 15px;

  .el-button {
    margin-right: 10px;
  }
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #e9e9ec;
  padding: 15px 20px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-dialog__footer {
  border-top: 1px solid #e9e9ec;
  padding: 10px 20px;
}

::v-deep .el-table {
  .el-input__inner {
    padding: 0 8px;
  }

  .el-select {
    width: 100%;
  }
}

.dialog-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style>
